from xml.etree import ElementTree

from lxml import etree
from lxml.etree import HTML

print('----------------------- xpath解析本地文件 -----------------------')
# # xpath解析本地文件
# tree: ElementTree = etree.parse('03_xpath.html')
# # print(f'解析本地文件：{tree.getroot()}')

# # 查找ul下面的li
# li_list = tree.xpath('//body/ul/li')
# print(f'查找ul下面的li：{li_list}')

# # 查找所有有id的属性的li标签
# # text()获取标签中的内容
# li_list = tree.xpath('//ul/li[@id]/text()')
# print(f'找到所有有id的属性的li标签：{li_list}')

# # 找到id为l1的li标签  注意引号的问题
# li_list = tree.xpath('//ul/li[@id="l1"]/text()')
# print(f'找到id为l1的li标签：{li_list}')

# # 查找到id为l1的li标签的class的属性值
# li = tree.xpath('//ul/li[@id="l1"]/@class')
# print(f'查询id为l1的li标签的class的属性值：{li}')

# # 查询id中包含l的li标签
# li_list = tree.xpath('//ul/li[contains(@id,"l")]/text()')
# print(f'查询id中包含l的li标签：{li_list}')

# # 查询id的值以l开头的li标签
# li_list = tree.xpath('//ul/li[starts-with(@id,"c")]/text()')
# print(f'查询id的值以l开头的li标签：{li_list}')

# # 查询id为l1和class为c1的
# li_list = tree.xpath('//ul/li[@id="l1" and @class="c1"]/text()')
# print(f'查询id为l1和class为c1的：{li_list}')

# # # 获取id为l1和l2的li标签的text()
# li_list = tree.xpath('//ul/li[@id="l1"]/text() | //ul/li[@id="l2"]/text()')
# print(f'获取id为l1和l2的li标签的text()：{li_list}')
# # 判断列表的长度
# print(f'列表的长度：{len(li_list)}')

print('----------------------- xpath解析网页 -----------------------')
import urllib.request

url = 'https://blog.csdn.net/tian330726/article/details/145924134'
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0'
}
# 请求对象的定制
request = urllib.request.Request(url=url, headers=headers)
# 模拟浏览器访问服务器
response = urllib.request.urlopen(request)
# 获取网页源码
content = response.read().decode('utf-8')
# 解析服务器响应的文件
tree: HTML = etree.HTML(content)

# 获取想要的数据  xpath的返回值是一个列表类型的数据
result = tree.xpath('//div[@class="blog-content-box"]/article/div/div[@id="content_views"]/div[@class="toc"]/ul/li/ul/li/a/text()')
print(f'获取列表的文本信息 ：{result}')

img = tree.xpath('//div[@class="blog-content-box"]/article/div/div[@id="content_views"]/p/img/@src')[0]
print(f'获取图片的src属性值：{img}')
# 下载图片
urllib.request.urlretrieve(img, '01-xpath.png')

